import 'package:flutter/material.dart';

class Bitmap {
  List<int> step = [];
  late List<Color> pixels;
  int x;
  int y;
  Color pixelColor = Color(0xff303032);

  int get maxCount => x * y;

  Color get color => pixelColor;

  Bitmap.fillWhite({required this.x, required this.y}) {
    pixels = List.filled(x * y, Colors.white);
  }

  Bitmap.fillBlack({required this.x, required this.y}) {
    pixels = List.filled(x * y, Colors.black);
  }

  Bitmap.fillMyColor({required this.x, required this.y}) {
    pixels = List.filled(x * y, color);
  }

  Color getPixel({required int dx, required int dy}) {
    if (dx >= 0 && dx < x && dy >= 0 && dy < y) {
      int value = dy * x + dx;
      return pixels[value];
    } else {
      return color;
    }
  }

  void setPixel({required int dx, required int dy, required Color color}) {
    if (dx >= 0 && dx < x && dy >= 0 && dy < y) {
      int value = dy * x + dx;
      pixels[value] = color;
      if (!step.contains(value)) {
        step.add(value);
      }
    }
  }

  void setPixelColor(Color color) {
    pixelColor = color;
  }

  void setStep(List<int> list) {
    step = list;
  }

  void clearStep() {
    step.clear();
  }

  Bitmap clone() {
    Bitmap bitmap = Bitmap.fillMyColor(x: x, y: y);
    for (int i = 0; i < bitmap.pixels.length; i++) {
      bitmap.pixels[i] = pixels[i];
    }
    return bitmap;
  }
}

class BitmapCache {
  List<Bitmap> bitmapList = [];
  int order = -1;

  void add(Bitmap bitmap) {
    bitmapList.removeRange(order + 1, bitmapList.length);
    bitmapList.add(bitmap);
    order++;
  }

  Bitmap? previous() {
    if (isHasPrevious()) {
      order--;
      if (order < 0) {
        return null;
      }
      return bitmapList[order];
    }
    return null;
  }

  Bitmap? next() {
    if (isHasNext()) {
      order++;
      return bitmapList[order];
    }
    return null;
  }

  bool isHasPrevious() {
    return order >= 0;
  }

  bool isHasNext() {
    return bitmapList.length - 1 > order;
  }

  void reset() {
    order = -1;
    bitmapList.clear();
  }
}
